<?php
/**
 * paypal接口类
 */
class Paypal{

    public $lastError; //Holds the last error encountered

    public $logIpn;//Do we need to log IPN results ?

    public $ipnLogFile;//File to log IPN results

    public $ipnResponse;//Payment gateway IPN response

    public $testMode;//Are we in test mode ?

    public $fields = array();//Field array to submit to gateway

    public $ipnData = array();//IPN post values as array

    public $gatewayUrl;//Payment gateway URL
    
    private $data = array();

    public function addField($field, $value){
        $this->fields["$field"] = $value;
    }

    /**
    * 生成支付代码
    * @param   array   $order      订单信息
    * @param   array   $payment    支付方式信息
    */
    function getCode($order,$payment){
       
		$str ='';
		$str.=$this->gatewayUrl;
		$i=0;
        foreach ($payment as $name => $value){
			if($i){
				 $str.='&'.$name.'='.$value;
			}else{
				 $str.='?'.$name.'='.$value;
			}
            $i++;
        }
		foreach ($order as $name => $value){
            if($i){
				 $str.='&'.$name.'='.$value;
			}else{
				 $str.='?'.$name.'='.$value;
			}
            $i++;
        }
    	return $str;
	}

   
	public function __construct($payment){
        $this->lastError = '';
        $this->logIpn = TRUE;
        $this->ipnResponse = '';
        $this->testMode = FALSE;
        $this->data     = $payment;
		$this->gatewayUrl = $payment['gateway'];
		
		//$this->enableTestMode();
	}

	/*开启测试paypal*/
    public function enableTestMode(){
		$this->text_ipn = 0;
        $this->testMode = TRUE;
        $this->gatewayUrl = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
    }


	public function getIpn(){
		return $this->text_ipn;
	}

    /*支付处理页面*/
	public function notify($order,$payment){//异步调用该方法
		
		$urlParsed  = parse_url($this->gatewayUrl);
		$postString = '';
		$fp = fsockopen($urlParsed[host], "80", $errNum, $errStr, 30);
		fclose($fp);
		$orderNo  = trim($_REQUEST['invoice']);
		
		if(!$fp){
			$this->failureDb($orderNo,-2);
			return false;
		}
		else{
			//F("TBL.paypal",array("b"=>$_POST,"e"=>$order,"f"=>$payment));
			if ($_POST['business']==$payment['business']){
				//&&$_POST['payment_status'] == "Completed" Pending
				$this->successDb($orderNo,1);
			    return true;
			}else{
				$this->failureDb($orderNo,-2);
				return false;
			}
			
		}
	}

	/*
	*支付返回处理
	*/
	function returnUrl($order,$payment){
		
	}

	/*处理订单成功*/
    function successDb($orderNo,$flag){
		$model = D("Order");
		$maps['order_no'] = $orderNo;
		$data['status']   = $flag;
		$data['paytime']  = time();
		
		$model->where($maps)->save($data);
    }

	/*处理订单失败*/
    function failureDb($orderNo,$flag){

        $model = D("Order");
		$maps['order_no'] = $orderNo;
		$data['status']   = $flag;
		
		$model->where($maps)->save($data);
    }

}
?>
